<?php

namespace App\Jobs\QiPao\Gift;

use App\Jobs\Job;
use App\Repositories\LogRepository;
use App\Services\Tools\IdempotentConsume;
use Illuminate\Support\Facades\Log;
use App\Exceptions\BasicException;
class GiftExpJob extends Job
{
    protected $data;    //通过give_gift表的id取出来的送礼记录
    protected $failId = [];
    const jobName = 'GiftExpJob';

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if(env('APP_ENV') != 'production'){
            Log::error('GiftExpJob:' . json_encode(['time' => getMillisecond(), 'data' => $this->data]));
        }
        try {
            $idempotentConsumeServer =  new IdempotentConsume();
            $data = $this->data;
            if(!empty($data)){
                $user_id = [];
                foreach ($data as $k=>$v){
                    if($idempotentConsumeServer->checkIdempotentRedisKey(self::jobName,$v['id'])){
                        if(!array_key_exists($v['user_id'],$user_id)){
                            $user_id[$v['user_id']] = [
                                'user_id' => $v['user_id'],
                                'gift_user' => $v['gift_user'],
                                'last_gift_give_id' => $v['id'],
                                'total_price' => $v['total_price'],
                            ];
                            $user_id[$v['user_id']]['give_ids'][] = $v['id'];
                        }else{
                            $user_id[$v['user_id']]['last_gift_give_id'] = $v['id'];
                            $user_id[$v['user_id']]['total_price'] += $v['total_price'];
                            $user_id[$v['user_id']]['give_ids'][] = $v['id'];
                        }
                    }
                }

                foreach ($user_id as $k=>$v){
                    app('model_user')->addVipExp($v['user_id'], $v['total_price'],1, $v['last_gift_give_id'],0,$v['gift_user']);
//                    $this->failId = array_merge($v['give_ids'],$this->failId);
                }
                if(!empty($this->failId)){
                    $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName,$this->failId);
                }
            }
        } catch (BasicException $exception) {
            foreach ($this->data as $k=>$v){
                $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName,$v['id']);
            }
            echo $exception->getMessage();
        } catch (\Exception $exception) {
            foreach ($this->data as $k=>$v){
                $idempotentConsumeServer->deleteIdempotentRedisKey(self::jobName,$v['id']);
            }
            Log::error('GiftExpJob:'.$exception->getMessage());
        }
    }

   /* public function fail($exception=null )
    {
        Log::error('ConnectionJob:'.$exception->getMessage());
    }*/
}
